package com.hcy.app.data.dao

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import com.hcy.app.data.GlobalState
import com.hcy.app.screen.cap.CapConfig
import kotlinx.coroutines.flow.first
import javax.inject.Inject


class SettingsRepository @Inject constructor(
    private val dataStore: DataStore<Preferences>
) {
    // 定义 Key
    companion object {
        val MUSIC_LOOP_MODE_KEY = intPreferencesKey("music_loop_mode")
        val MUSIC_CURRENT_SONG_ID_KEY = longPreferencesKey("music_current_song_id")

        val CAP_CONFIG_USERNAME_KEY = stringPreferencesKey("cap_config_username")
        val CAP_CONFIG_PASSWORD_KEY = stringPreferencesKey("cap_config_password")
        val CAP_CONFIG_SERADDR_KEY = stringPreferencesKey("cap_config_seraddr")
        val CAP_ACCESS_TOKEN_KEY = stringPreferencesKey("cap_access_token")
        val CAP_TOKEN_EXPIRES_KEY = longPreferencesKey("cap_token_expires")
        val CAP_USERNAME_KEY = stringPreferencesKey("cap_username")
        val CAP_ROLES_KEY = stringPreferencesKey("cap_roles")


    }

    // 保存循环模式（0-单曲，1-列表，2-随机）
    suspend fun saveLoopMode(mode: Int) {
        dataStore.edit { preferences ->
            preferences[MUSIC_LOOP_MODE_KEY] = mode
        }
    }

    suspend fun getLoopMode(): Int {
        return dataStore.data.first()[MUSIC_LOOP_MODE_KEY]?:0
    }

    suspend fun getCurrentSong(): Long  {
        return dataStore.data.first()[MUSIC_CURRENT_SONG_ID_KEY]?:0L
    }

    // 保存上一次播放音乐的下标
    suspend fun saveSongIndex(id: Long) {
        dataStore.edit { preferences ->
            preferences[MUSIC_CURRENT_SONG_ID_KEY] = id
        }
    }

    suspend fun getCapConfig(): CapConfig{
        val username= dataStore.data.first()[CAP_CONFIG_USERNAME_KEY]?:""
        val password= dataStore.data.first()[CAP_CONFIG_PASSWORD_KEY]?:""
        val serAddr= dataStore.data.first()[CAP_CONFIG_SERADDR_KEY]?:""
        return CapConfig(username,password,serAddr)
    }

    suspend fun saveCapConfig(conf:CapConfig){
        dataStore.edit { preferences ->
            preferences[CAP_CONFIG_USERNAME_KEY] = conf.username
            preferences[CAP_CONFIG_PASSWORD_KEY] = conf.password
            preferences[CAP_CONFIG_SERADDR_KEY] = conf.serAddr
        }
    }

    suspend fun saveCapToken(token: String, expires :Long, roles: List<String>, username: String){
        val rolesStr= roles.joinToString(",")
        dataStore.edit { preferences ->
            preferences[CAP_ACCESS_TOKEN_KEY] = token
            preferences[CAP_TOKEN_EXPIRES_KEY]=expires
            preferences[CAP_USERNAME_KEY]=username
            preferences[CAP_ROLES_KEY]=rolesStr
        }
        GlobalState.CapTokenExpires = expires
        GlobalState.CapToken = token
        GlobalState.CapUsername = username
        GlobalState.CapRoles = roles
    }

    suspend fun loadCapToken(){
        GlobalState.CapTokenExpires = dataStore.data.first()[CAP_TOKEN_EXPIRES_KEY] ?: 0L
        GlobalState.CapToken = dataStore.data.first()[CAP_ACCESS_TOKEN_KEY] ?: ""
        GlobalState.CapUsername = dataStore.data.first()[CAP_USERNAME_KEY]?:""
        val rolesStr= dataStore.data.first()[CAP_ROLES_KEY]?:""
        GlobalState.CapRoles = rolesStr.split(",")
    }

}
//
//object RepositoryFactory {
//    // 懒初始化 DataStore（确保单例）
//    private val dataStore by lazy {
//        PreferenceDataStoreFactory.create(
//            produceFile = {
//                File("${context.filesDir}/datastore/settings.preferences_pb")
//            }
//        )
//    }
//
//    // 暴露 Repository 实例
//    fun createSettingsRepository(context: Context): SettingsRepository {
//        return SettingsRepository(dataStore)
//    }
//}
